<template>
<div>
  <div style="padding-bottom:5px">
  <el-select  v-model="select"  @change = "grsChange">
    <el-option  v-for="(item,i) in graphsList"
    :key="item.grsNo"
    :label="item.grsName"
    :value= "i">
    </el-option>
   </el-select>
      <el-button-group>
       <el-button type="primary" icon="plus" size="small" @click="addDashBorad()">添加设备页</el-button>
       <el-button type="primary" icon="edit" size="small" @click="editDashBorad()">编辑设备页</el-button>
       <el-button type="primary" icon="delete" size="small" @click="delDashBorad()">删除设备页</el-button>
       <el-button type="primary" icon="share" size="small" @click="sendToMenu()">发布到菜单</el-button>

     </el-button-group>
     <el-button-group>
       <el-button type="primary" icon="setting" size="small" @click="setWidget()">选择设备</el-button>
       <!-- <el-button type="primary" icon="picture " size="small" @click="fullScreen()">全屏显示</el-button> -->
       <el-button type="primary" icon="setting" size="small" @click="saveWidget()">保存布局</el-button>

     </el-button-group>
   </div>
     <designer ref="designer" :keyMap="keyMap" :parentDesignerData='desigerData'  :gridsterId="graphId"></designer>


       <el-dialog :modal=true v-model="dashBoradDialogVisible">
         <el-form :model="dashBoradForm" ref="dashBoradForm" label-width="100px" >
           <el-form-item label="操作">
             <el-button type="primary" @click="saveDashBorad()" size="small">保存</el-button>
             <el-button @click="dashBoradDialogVisible = false" size="small">取消</el-button>
           </el-form-item>
           <el-form-item label="名称" prop="grsName">
             <el-input v-model="dashBoradForm.grsName"></el-input>
           </el-form-item>
           <el-form-item label="编号" prop="grsNo">
             <el-input v-model="dashBoradForm.grsNo"></el-input>
           </el-form-item>
           <el-form-item label="参数" prop="params">
             <el-input type="textarea" v-model="dashBoradForm.params"></el-input>
           </el-form-item>
           <el-form-item label="图形样式" prop="style">
             <el-input type="textarea" v-model="dashBoradForm.style"></el-input>
           </el-form-item>
           <el-form-item label="备注" prop="remark">
             <el-input type="textarea" v-model="dashBoradForm.remark"></el-input>
           </el-form-item>
         </el-form>
       </el-dialog>

       <el-dialog :modal=true v-model="routerDialogVisible">

         <component :is="currentView" ref="devGraphChooser"  transition="fade" transition-mode="out-in" keep-alive :result="devGraphList"></component>
         <div style="padding-bottom:5px;float:right" >
           <el-button type="primary" icon="save" size="small" @click="draw()">确定</el-button>
           <el-button type="primary" icon="cancel" size="small" @click="routerDialogVisible = false">取消</el-button>
         </div>
       </el-dialog>

</div>


</template>

<script>
import designer from './designer.vue'
import devGraphChooser from './devGraphChooser.vue'
import api from 'api/graph.js'

export default {
  name: 'devStatus',

  data() {
    var t = new Date();
    require("jquery.fullscreen");
    return {
      keyMap: {outEdit:'true'},
      desigerData:{},
      graphsList: [],
      select:'',
      graphsType:'11',
      inputParams:{},
      graphId:"dashboard-"+t.getTime(),
      dashBoradDialogVisible:false,
      routerDialogVisible:false,
      currentView:null,
      dashBoradForm:{
        grsName:'',
        grsType:'11',
        grsNo:'',
        remark:''
      },
      devGraphList:[],
      handelMode:""
    }
  },
  mounted() {
    this.queryData();
  },
  methods: {
    queryData() {
      api.listGraphs(this.graphsType).then((response) => {
        var data = response.data;
        this.graphsList = data;
        if(this.handelMode == "insert"){//新增flag，选择最后一个选项
          this.select = this.graphsList.length - 1;
          this.dashBoradForm = this.graphsList[this.select];
          this.desigerData={
            grsNo:this.dashBoradForm.grsNo
          };
          this.handelMode = "";
        }else if(this.select == ''){//没有选择选择第一个选项
          if(data[0]){
            this.select = 0;
            this.dashBoradForm = this.graphsList[this.select];
            this.desigerData={
              grsNo:this.dashBoradForm.grsNo
            };
          }

        }else if(!data||data.length==0){//没有选择选择第一个选项
          this.select = '';
          this.dashBoradForm ={
                   grsName:'',
                    grsType:'11',
                    grsNo:'',
                    remark:''};
          this.desigerData={
            grsNo:''
          };
        }else{
          this.$refs.designer.init();
        }
      }).catch((err) =>{
          console.error(err);
      });
    },
    grsChange(){
      if(this.graphsList[this.select]){
        this.dashBoradForm = this.graphsList[this.select];
        this.desigerData={
          grsNo:this.dashBoradForm.grsNo
        };
      }
    },
    fullScreen(){
      $('#'+this.graphId).fullScreen();
    },
    addDashBorad(){
      this.dashBoradForm = {
              grsName:'',
              grsType:'11',
              grsNo:'',
              remark:''
      };
      this.handelMode = "insert";
      this.dashBoradDialogVisible = true;
    },
    editDashBorad(){
      this.dashBoradForm = this.graphsList[this.select];
      this.dashBoradDialogVisible = true;
    },
    saveDashBorad(){
      //表单信息
      var formData = this.dashBoradForm;
      api.saveGraphs(formData).then((response) => {
        //同步表单数据（主要是新增的是获取新的ID）
        this.dashBoradForm = response.data;
        this.dashBoradDialogVisible = false;
        this.$emit("getMenuList");
        this.queryData();
        this.$message({
          showClose: true,
          message: "保存成功！"
        });
      }).catch((err) => {
        this.$message({
          showClose: true,
          message: "保存失败："+err.data.errorMsg
        });
      });
    },
    delDashBorad(){
      this.$confirm('是否删除该监控页?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.deleteGraphs(this.dashBoradForm["id"]).then((response) => {
          this.select = '';
          this.$emit("getMenuList");
          this.queryData();
        }).catch((err) =>{
            console.error(err);
        });
      });
    },
    setWidget(){
      if(this.graphsList.length==0||(this.select==''&&this.select!=0)){
        this.$message({
          showClose: true,
          message: '请先选择或添加一个监控页！'
        });
        return false;
      }
      this.currentView = devGraphChooser;
      this.routerDialogVisible = true;
    },
    draw(){
      //获取选中的图形列表
      var devs = this.$refs.devGraphChooser.selectDevs;
      var widgetJson = [];
      if(devs.length==0){
        this.$message({
          showClose: true,
          message: '至少选中一个图形！'
        });
        return false;
      }
      if(devs.length>25){
        this.$message({
          showClose: true,
          message: '最多选择24个图形，请注意拆分业务！'
        });
        return false;
      }

      for(var i=0;i<devs.length;i++){
        var y = parseInt(i/3)*7+1;
        var x = (i%4)*2+1;
        var obj = devs[i];
        widgetJson.push({
          "col":x,
          "row":y,
          "size_x":2,
          "size_y":7,
          "form":{
            "chartName":obj.name,
            "chartType":"device",
            "refFlag":"0",
            "refMs":"30000",
            "option":{
              "value":"host-item-report.score",
              "scoreKey":"score",
              "backgroundColor":"white",
              "fontColor":"black",
              "params":JSON.stringify({hostid:obj.id})
            }
          }
        });
      }
      this.dashBoradForm.widgetData = JSON.stringify(widgetJson);
      this.saveDashBorad();
      this.routerDialogVisible = false;
    },
    sendToMenu(){
      this.$confirm('是否发布监控页到【设备监控】菜单下?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var formData = this.dashBoradForm;
        api.sendToMenu(formData,'ReportMgm','Device Monitor').then((response) => {
          //同步表单数据（主要是新增的是获取新的ID）
          this.$emit("getMenuList");
        }).catch((err) => {
          console.error(err);
        });
      });

    },
    saveWidget(){
      this.$refs.designer.doSave(true);
    }
  },
  components: {
    designer,devGraphChooser
  }
}
</script>
